package com.yang.jackson;
import java.io.IOException;
import java.util.Map;

import org.junit.Test;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson {

	/**
	 * 将java对象转换为json字符串
	 */
	@Test
	public void test1() {
		ObjectMapper mapper = new ObjectMapper();
		Cat cat = new Cat("blue", 10);
		try {
			System.out.println(mapper.writeValueAsString(cat));
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 组装json字符串
	 */
	@Test
	public void test3() {
		ObjectMapper mapper = new ObjectMapper();
		JsonGenerator generator = null;
		try {
			generator = mapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
			generator.writeStartObject();

			generator.writeFieldName("aa");
			generator.writeBoolean(true);

			generator.writeBooleanField("aa", true);

			generator.writeArrayFieldStart("bb");

			generator.writeNull();
			generator.writeNumber(2);

			generator.writeEndArray();

			generator.writeObjectFieldStart("cc");

			generator.writeNumberField("dd", 22);

			generator.writeEndObject();

			generator.writeEndObject();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (generator != null) {
				try {
					generator.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 将json字符串转为java对象 java对象必须含有无参的构造方法
	 *
	 */
	@Test
	public void test2() {
		ObjectMapper mapper = new ObjectMapper();
		String content = "{\"color\":\"blue\",\"age\":10}";
		try {
			Cat cat = mapper.readValue(content, Cat.class);
			System.out.println(cat);
			Map<String, Object> map = mapper.readValue(content, Map.class);
			System.out.println(map.get("color"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
